package com.ayou.session.defaults;

import com.ayou.binding.MapperProxyFactory;
import com.ayou.executor.Executor;
import com.ayou.mapping.MappedStatement;
import com.ayou.session.Configuration;
import com.ayou.session.SqlSession;
import com.demo.mapper.UserMapper;

import java.util.List;
import java.util.Map;

/**
 * @description: 默认sqlSession实现
 * @author: ayouman
 * @date: 2024/7/2 14:31
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;
    private Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    public <T> T selectOne(String mpId, Map<String, Object> params) {
        List<T> result = selectList(mpId, params);
        if (result.isEmpty()) {
            return null;
        } else if (result.size() == 1) {
            return result.get(0);
        } else {
            throw new RuntimeException("Too many results");
        }
    }

    @Override
    public <T> List<T> selectList(String mpId, Map<String, Object> params) {
        MappedStatement mappedStatement = this.configuration.getMappedStatement(mpId);
        return this.executor.query(mappedStatement, params);
    }

    @Override
    public int insert(String mpId, Map<String, Object> params) {
        MappedStatement mappedStatement = this.configuration.getMappedStatement(mpId);
        return this.executor.update(mappedStatement, params);
    }

    @Override
    public int delete(String mpId, Map<String, Object> params) {
        MappedStatement mappedStatement = this.configuration.getMappedStatement(mpId);
        return this.executor.update(mappedStatement, params);
    }

    @Override
    public int update(String mpId, Map<String, Object> params) {
        MappedStatement mappedStatement = this.configuration.getMappedStatement(mpId);
        return this.executor.update(mappedStatement, params);
    }

    @Override
    public <T> T getMapper(Class<T> clazz) {
        return MapperProxyFactory.getProxy(clazz, this);
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }
}
